﻿package {
	import flash.display.MovieClip;
	import flash.events.IEventDispatcher;
	
	import com.mixmedia.event.EventDispatcherUtils;
	import com.mixmedia.motion.MotionTween;
	import com.mixmedia.motion.MotionTweenEvent;
	import com.mixmedia.navigation.Navigation;
	import com.mixmedia.navigation.NavigationEvent;
	import com.mixmedia.net.LoadSWF;
	import com.mixmedia.net.Loader;
	import com.mixmedia.net.LoaderEvent;	

	/**
 * @author Colin
 */
	public class Content extends MovieClip implements IEventDispatcher,IFASTEventDispatcher{
		private var base:MovieClip;
		private var loader:Loader;
		private var prefix:String;
		private var currentNavKey:String;
		private var fadein:MotionTween;
		private var fadeout:MotionTween;
		private var targetName: String;
		private var extension : String;
		private var loadedMovie:MovieClip;
	
		public function Content(){
			this.base = this;

			loader = new Loader(new LoadSWF(base));
			loader.setPreloader(base);
			loader.setErrorIcon(base);
			loader.when(LoaderEvent.READY, this,onLoadContentAndFadeIn);
			loadedMovie = MovieClip(loader.getTargetContainer());

			var para:Array = base.name.split('$');
			targetName	= para[1]==null?"":para[1];
			prefix		= para[2]==null?"":para[2];
			extension   = para[3]==null?"swf":para[3];
	
			fadein  = new MotionTween(MovieClip(loader.getTargetContainer()),{a:100});
			fadeout = new MotionTween(MovieClip(loader.getTargetContainer()),{a:0});
			fadeout.when(MotionTweenEvent.END, this, onFadeOutAndLoad);
	
			var n:Navigation = Navigation.instance();
			n.when(NavigationEvent.CHANGE, this, onNavChange);
		}
	
		private function onNavChange(e:NavigationEvent):void{
			//if targetName is empty, load only 
			var navTargetIsEmpty:Boolean = (e.targetContainer==""||e.targetContainer==null);
	 		var criteria1:Boolean = (targetName==""&&navTargetIsEmpty);
	 		var criteria2:Boolean = (navTargetIsEmpty==false&&e.targetContainer==targetName);
			if(criteria1==false&&criteria2==false)return;
	
			currentNavKey = e.navKey;
			transitionOut();
		}
	
		private function transitionOut():void{
			fadeout.startTween();
		}
	
		private function onFadeOutAndLoad():void {
			loadAction();
		}
	
		private function onLoadContentAndFadeIn():void{
			if(Navigation.instance().getNavStackRequests()!=null)Navigation.instance().nextSection();
			fadein.startTween();
		}
	
		private function loadAction():void{
			loader.load(prefix+currentNavKey+"."+extension);	
		}
	
		public function when(eventType : String, whichObject : Object, callFunction : Function) : void {
			EventDispatcherUtils.when(this,eventType,whichObject,callFunction);
		}
	}
}